package com.cloud.school.bus.teacherhelper.modules.home;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.media.ThumbnailUtils;
import android.os.Bundle;
import android.provider.MediaStore.Video.Thumbnails;
import android.text.Editable;
import android.text.InputFilter;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.ViewFlipper;
import android.widget.AdapterView.OnItemClickListener;

import com.android.support.jhf.handlerui.HandlerPostUI;
import com.android.support.jhf.handlerui.HandlerToastUI;
import com.android.support.jhf.network.NetworkClient;
import com.android.support.jhf.network.loopj.android.http.ResponseHandlerInterface;
import com.android.support.jhf.universalimageloader.core.ImageLoader;
import com.android.support.jhf.universalimageloader.core.listener.SimpleImageLoadingListener;
import com.android.support.jhf.utils.ImageUtil;
import com.android.support.jhf.utils.ToolUtils;
import com.cloud.school.bus.teacherhelper.R;
import com.cloud.school.bus.teacherhelper.base.activity.BaseActivity;
import com.cloud.school.bus.teacherhelper.base.anim.swap3d.RotationHelper;
import com.cloud.school.bus.teacherhelper.base.database.VideoIgnoreDB;
import com.cloud.school.bus.teacherhelper.base.dialog.CustomAlertDialog;
import com.cloud.school.bus.teacherhelper.base.dialog.CustomListDialog;
import com.cloud.school.bus.teacherhelper.base.dialog.CustomListDialog.CustomListDialogItem;
import com.cloud.school.bus.teacherhelper.base.view.TitleNavBarView;
import com.cloud.school.bus.teacherhelper.entitys.Picture;
import com.cloud.school.bus.teacherhelper.entitys.Student;
import com.cloud.school.bus.teacherhelper.entitys.UploadFile;
import com.cloud.school.bus.teacherhelper.entitys.LoginSetting.PhotoTag;
import com.cloud.school.bus.teacherhelper.modules.SlidingActivity;
import com.cloud.school.bus.teacherhelper.modules.home.adapter.EditContentAdapter;
import com.cloud.school.bus.teacherhelper.modules.home.camera.CustomCameraActivity;
import com.cloud.school.bus.teacherhelper.modules.home.recorder.VideoPlayActivity;
import com.cloud.school.bus.teacherhelper.modules.home.view.EditContentView;
import com.cloud.school.bus.teacherhelper.modules.home.view.SelectedStuView;
import com.cloud.school.bus.teacherhelper.modules.notice.adapter.StuSelectAdapter;
import com.cloud.school.bus.teacherhelper.modules.uploadlist.uploadutils.UploadFileUtils;
//import com.cloud.school.bus.teacherhelper.modules.uploadlist.uploadutils.UploadUtils;
import com.cloud.school.bus.teacherhelper.protocol.classstudent.GetClassinfoRequest;
import com.cloud.school.bus.teacherhelper.protocol.classstudent.GetClassinfoResponse;

/**
 * 照完相或者是录像完成，上传文件或者照片，选择学生，填写内容和照片标签都再一个节目
 * 
 * @author jiahongfei
 * 
 */
public class UploadFileStuSelectedActivity extends BaseActivity {

	private EditText mContentEditText;
	private TextView mNumberTextView;
	private ImageView mImageView;
	private ImageView mPlayImageView;
	private TitleNavBarView mTitleNavBarView;
	private GridView mPhotoGridView;
	private EditContentAdapter mEditContentAdapter;

	private GridView mStudentGridView;
	private StuSelectAdapter mStuSelectAdapter;

	private String mTitleString;
	private Picture mPicture;
	/** -1录像完成，-2照相完成 */
	private int mIndex;
	private UploadFile mUploadFile;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_uload_file_student_selected);

		init();
	}

	@Override
	protected void init() {

		mPicture = (Picture) getIntent().getSerializableExtra("picture");
		mIndex = getIntent().getIntExtra("index", 0);
		mTitleString = getIntent().getStringExtra("title");

		mPlayImageView = (ImageView) findViewById(R.id.playImageView);
		mImageView = (ImageView) findViewById(R.id.imageView);
		ViewGroup imageLayout = (ViewGroup) findViewById(R.id.imageLayout);
		if (mPicture.getPicturePath().endsWith("MP4")
				|| mPicture.getPicturePath().endsWith("mp4")) {
			Bitmap bitmap = ThumbnailUtils.createVideoThumbnail(mPicture
					.getPicturePath().replace("file:///", "/"),
					Thumbnails.MINI_KIND);
			if (null != bitmap) {
				mImageView.setImageBitmap(bitmap);
			}
			mPlayImageView.setVisibility(View.VISIBLE);
			imageLayout.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View arg0) {
					// 播放视频
					Intent intent = new Intent(mContext,
							VideoPlayActivity.class);
					intent.putExtra("path",
							mPicture.getPicturePath().replace("file:///", "/"));
					intent.putExtra("flag", 1);
					startActivity(intent);
				}
			});
		} else {
			imageLayout.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View arg0) {
					// 显示图片
					Intent intent = new Intent(mContext,
							CameraBigPictureActivity.class);
					intent.putExtra("flag", 1);
					intent.putExtra("picPath", mPicture.getPicturePath()
							.replace("file:///", "/"));
					startActivityForResult(intent, 0);
				}
			});
			mPlayImageView.setVisibility(View.GONE);
			ImageLoader.getInstance().displayImage(mPicture.getPicturePath(),
					mImageView, mApplication.mCacheDisplayImageOptions,
					new SimpleImageLoadingListener() {
						@Override
						public void onLoadingComplete(String imageUri,
								View view, Bitmap loadedImage) {
							ImageView imageView = (ImageView) view;
							// imageView.setImageBitmap(loadedImage);
							if (imageUri.startsWith("http://")) {
								imageView.setImageBitmap(loadedImage);
							} else if (imageUri.startsWith("file:///")) {
								ImageUtil.setRotaingImageBitmap(
										imageUri.replace("file:///", "/"),
										loadedImage, imageView);
							} else {
								ImageUtil.setRotaingImageBitmap(imageUri,
										loadedImage, imageView);
							}
						}
					});
		}
		mPhotoGridView = (GridView) findViewById(R.id.photoGridView);

		if (ToolUtils.isLanguage(mContext, "zh")) {
			// 系统汉语的时候
			mEditContentAdapter = new EditContentAdapter(mContext,
					mApplication.mLoginSetting.photoTagList.get(0));
		} else {
			// 系统英文的时候
			mEditContentAdapter = new EditContentAdapter(mContext,
					mApplication.mLoginSetting.photoTagList.get(1));
		}
		mEditContentAdapter.clearSelected();
		mPhotoGridView.setAdapter(mEditContentAdapter);

		mContentEditText = (EditText) findViewById(R.id.contentEditText);
		mNumberTextView = (TextView) findViewById(R.id.numberTextView);

		mUploadFile = new UploadFile();
		mUploadFile.picPathString = mPicture.getPicturePath();
		mUploadFile.picSizeString = getPicSize(mUploadFile.picPathString) + "";
		mUploadFile.picFileString = getPicName(mUploadFile.picPathString);
		mUploadFile.studentIdList = new ArrayList<String>();
		// mUploadFile.classuid = mApplication.mClassInfo.uid;
		mUploadFile.intro = null;
		mUploadFile.photoTag = null;
		mUploadFile.teacherid = mApplication.mTeacher.teacherid;

		getClassinfo(new Runnable() {

			@Override
			public void run() {
				mUploadFile.classuid = mApplication.mClassInfo.uid;
			}
		});

		mStudentGridView = (GridView) findViewById(R.id.studentGridView);
		mStuSelectAdapter = new StuSelectAdapter(mContext,
				mApplication.mStudentList);
		mStuSelectAdapter.clearSelected();
		mStudentGridView.setAdapter(mStuSelectAdapter);

		setListener();
		setTitleNavBar();
	}

	public void getClassinfo(final Runnable runnable) {
		if (null == mApplication.mClassInfo || null == mApplication.mTeacher
				|| null == mApplication.mStudentList) {
			NetworkClient.getNetworkClient().GetRequest(
					new GetClassinfoRequest(this), new GetClassinfoResponse() {
						@Override
						public void onResponse(
								ResponseHandlerInterface responseHandlerInterface) {

							if ("1".equals(code)) {
								mApplication.mClassInfo = classInfo;
								mApplication.mTeacher = teacher;
								mApplication.mStudentList = studentList;
								HandlerPostUI.getHandlerPostUI(runnable);
							} else if ("-4".equals(code)) {
								// HandlerToastUI.getHandlerToastUI(
								// SlidingActivity.this, "不存在班级");
							}
						}
					});
		} else {
			HandlerPostUI.getHandlerPostUI(runnable);
		}
	}

	@Override
	protected void setListener() {
		mContentEditText.setFilters(new InputFilter[] { new InputFilter() {

			@Override
			public CharSequence filter(CharSequence source, int start, int end,
					Spanned dest, int dstart, int dend) {

				if (source.equals("\n")) {
					return "";
				}
				return source;
			}

		} });

		mContentEditText.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence arg0, int arg1, int arg2,
					int arg3) {
				mNumberTextView.setText(arg0.length() + "/280");
			}

			@Override
			public void beforeTextChanged(CharSequence arg0, int arg1,
					int arg2, int arg3) {

			}

			@Override
			public void afterTextChanged(Editable arg0) {

			}
		});
		mPhotoGridView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TextView textView = (TextView)
				// arg1.findViewById(R.id.textView);
				// textView.setSelected(!textView.isSelected());
			}
		});
	}

	@Override
	public void setTitleNavBar() {

		mTitleNavBarView = (TitleNavBarView) findViewById(R.id.titleNavBarView);
		mTitleNavBarView.setMessage(mTitleString);
		mTitleNavBarView.setLeftButtonOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// 返回
				cancel();
			}
		});
		mTitleNavBarView.setRightButtonImageString(
				R.drawable.btn_title_upload_pic_xml, "", R.color.text_blue);
		mTitleNavBarView.setRightButtonOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {

				if (null == mApplication.mClassInfo) {
					getClassinfo(new Runnable() {

						@Override
						public void run() {

							mUploadFile.classuid = mApplication.mClassInfo.uid;

							upload();

						}
					});
				} else {
					upload();

				}
			}
		});
	}

	private void upload() {
		// 请选择学生
		for (int i = 1; i < mStuSelectAdapter.getCount(); i++) {
			Student student = (Student) mStuSelectAdapter.getItem(i);
			if (student.isSelected) {
				mUploadFile.studentIdList.add(student.studentid);
			}
		}

		int photoIndex = -1;
		String photoTag = "";
		photoIndex = mEditContentAdapter.getCurrentItem();
		if (-1 != photoIndex) {
			photoTag = ((PhotoTag) mEditContentAdapter.getItem(photoIndex)).photoTag;
		}
		mUploadFile.photoTag = photoTag;
		mUploadFile.intro = mContentEditText.getText().toString();

		if (0 == mUploadFile.studentIdList.size()) {
			HandlerToastUI.getHandlerToastUI(mContext, "请关联学生");
		} else {
			// 都关联了学生
			// 返回上一级
			if (-1 == mIndex) {
				Intent intent = new Intent(mContext, SlidingActivity.class);
				intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				startActivity(intent);
			} else {
				Intent intent = new Intent();
				intent.putExtra("index", mIndex);
				setResult(Activity.RESULT_OK, intent);
			}
			finish();
			saveUploadFile();
		}
	}

	private void showSaveVideoDialog(final boolean flag) {
		CustomListDialog customListDialog = CustomListDialog
				.getCustomListDialog(mContext,
						com.android.support.jhf.R.style.DialogFromDownToUp);
		final List<CustomListDialogItem> customListDialogItems = new ArrayList<CustomListDialog.CustomListDialogItem>();
		CustomListDialogItem customListDialogItem1 = new CustomListDialogItem();
		customListDialogItem1.text = getString(R.string.save_caogao);
		customListDialogItem1.textColor = getResources().getColor(
				R.color.btn_bg_blue);
		customListDialogItem1.textSize = 18;
		customListDialogItems.add(customListDialogItem1);
		CustomListDialogItem customListDialogItem2 = new CustomListDialogItem();
		customListDialogItem2.text = getString(R.string.dont_save);
		customListDialogItem2.textColor = getResources().getColor(
				R.color.btn_bg_blue);
		customListDialogItem2.textSize = 18;
		customListDialogItems.add(customListDialogItem2);

		customListDialog.setMessage(customListDialogItems);
		customListDialog.setTitle(getString(R.string.save_draft));
		customListDialog.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				CustomListDialogItem customListDialogItem = customListDialogItems
						.get(arg2);
				if (0 == arg2) {
					// 保存草稿箱
				} else if (1 == arg2) {
					// 不保存
					File videoFile = new File(mPicture.getPicturePath()
							.replace("file:///", "/"));
					videoFile.delete();
					// imageFile.delete();

					if (flag) {
						Intent intent = new Intent();
						intent.putExtra("index", mIndex);
						setResult(Activity.RESULT_OK, intent);
					}
				}
				if (!flag) {
					Intent intent = new Intent(mContext, SlidingActivity.class);
					intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					startActivity(intent);
				}
				finish();
			}
		});
		customListDialog.show();
	}

	private void cancel() {
		if (-1 == mIndex) {
			// 是否保存视频
			showSaveVideoDialog(false);
		} else {
			if (mPicture.getPicturePath().endsWith("MP4")
					|| mPicture.getPicturePath().endsWith("mp4")) {
				showSaveVideoDialog(true);
			} else {
				CustomAlertDialog customAlertDialog = new CustomAlertDialog(
						mContext, R.style.CustomAlertDialog);
				customAlertDialog.setTitleMessage(getString(R.string.tips),
						Color.BLACK);
				customAlertDialog
						.setMessage(getString(R.string.cancel_sending_this_photos));
				customAlertDialog.setLeftButton(getString(R.string.yes),
						new OnClickListener() {

							@Override
							public void onClick(View arg0) {
								((Activity) mContext).finish();
							}
						});
				customAlertDialog.setRightButton(getString(R.string.no),
						new OnClickListener() {

							@Override
							public void onClick(View arg0) {

							}
						});
				customAlertDialog.show();
			}
		}
	}

	private void saveUploadFile() {
		// new Thread(new Runnable() {
		//
		// @Override
		// public void run() {
		List<UploadFile> uploadFiles = new ArrayList<UploadFile>();
		uploadFiles.add(mUploadFile);

		// 添加忽略数据库
		VideoIgnoreDB videoIgnoreDB = VideoIgnoreDB.getVideoIgnoreDB(mContext);
		videoIgnoreDB.putInsert(mPicture);
		videoIgnoreDB.close();
		// 保存数据
		// UploadUtils.getUploadUtils().setContext(mContext);
		// UploadUtils.getUploadUtils().setUploadFileDB(uploadFiles);
		// UploadUtils.getUploadUtils().uploadFileService();
		UploadFileUtils.getUploadUtils().setContext(mContext);
		UploadFileUtils.getUploadUtils().setUploadFileDB(uploadFiles);
		UploadFileUtils.getUploadUtils().uploadFileService();
		// }
		// }).start();
	}

	private String getPicName(String picPathString) {
		String picNameString = "";
		picNameString = picPathString
				.substring(picPathString.lastIndexOf("/") + 1);
		return picNameString;
	}

	private int getPicSize(String picPathString) {
		int size = 0;
		try {
			picPathString = picPathString.replace("file:///", "/");
			FileInputStream inputStream = new FileInputStream(new File(
					picPathString));
			try {
				size = inputStream.available();
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				try {
					inputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		return size;
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			cancel();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

}
